package com.shushan.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.fgchecker.AppCheckerTimeOut;
import com.shushan.base.Constants;
import com.shushan.home.TabHomeActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.util.SystemUtils;

/**
 * @ClassName: WechatShareRTAService
 * @Desciption: 微信分享监听服务
 * @author: yichaohua
 * @date: 2018-10-17
 */
public class WechatShareRTAService  extends Service {

    private final static String TAG = "WechatShareRTAService";

    private String allowPackName = Constants.ALLOW_WECHAT_PACK_NAME;
    private AppCheckerTimeOut appChecker;
    private BabyApplication babyApplication = BabyApplication.getInstance();

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "onCreate()");

        startChecker();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        appChecker.setmTimeoutCounter(0);

        if(intent != null){
            allowPackName = intent.getStringExtra("allowPackName");
        }

        Log.i(TAG, "onStartCommand() " + "allowPackName=" + allowPackName);

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i(TAG,"onDestroy()");

        stopChecker();
    }

    private void startChecker() {
        appChecker = new AppCheckerTimeOut();
        appChecker.when(getPackageName(), new AppCheckerTimeOut.Listener() {
            @Override
            public void onForeground(String packageName) {
                Log.i(TAG, "Our app is in the foreground.");

                SystemUtils.sendForegActivity(babyApplication,TabHomeActivity.class);
                stopSelf();
            }
        })
        .whenOther(new AppCheckerTimeOut.Listener() {
            @Override
            public void onForeground(String packageName) {
                Log.i(TAG,"onForeground packageName=" + packageName);
                if(allowPackName.equals(packageName) || SystemUtils.isSparePackName(packageName)){
                    return;
                }

                SystemUtils.sendForegActivity(babyApplication,TabHomeActivity.class);
                stopSelf();
            }
        })
        .whenTimeOut(new AppCheckerTimeOut.Listener() {
            @Override
            public void onForeground(String packageName) {
                Log.i(TAG,"time out packageName=" + packageName);

                SystemUtils.sendForegActivity(babyApplication,TabHomeActivity.class);
                stopSelf();
            }
        })
        .timeout(3000)
        .start(this);
    }

    private void stopChecker() {
        appChecker.stop();
    }
}
